package com.kylin.common.core.mybatis.mapper.probider;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;
import com.kylin.common.core.entity.TreeEntity;
import com.kylin.common.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * 树操作支持扩展类
 *
 * @author wuhao
 * @version 1.0 - 2019-08-13
 */
public class TreeSqlProvider {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 更新子节点信息
     * @param oldEntity 旧对象
     * @param newEntity 新对象
     * @return
     * @author wuhao
     * @since 2.6.0 - 2022/6/26
     */
    public String updateChild(TreeEntity<?> oldEntity,TreeEntity<?> newEntity) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(newEntity.getClass());
        String tableName = tableInfo.getTableName();
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(tableName).append("\n");
        sql.append("set").append("\n");
        sql.append(String.format("parent_ids = REPLACE(parent_ids, '%s','%s'),",oldEntity.getParentIds(),newEntity.getParentIds())).append("\n");
        sql.append(String.format("tree_labels = REPLACE(tree_labels, '%s','%s'),",oldEntity.getTreeLabels(),newEntity.getTreeLabels())).append("\n");
        sql.append(String.format("tree_sorts = REPLACE(tree_sorts, '%s','%s')",oldEntity.getTreeSorts(),newEntity.getTreeSorts())).append("\n");
        sql.append("where parent_ids like '%").append(newEntity.getId()).append(",%'");

        return sql.toString();
    }

    /**
     * 根据id获取父节点信息
     * @param entity 对象
     * @param id 主键id
     * @return
     * @author wuhao
     * @since 2.6.0 - 2023/1/2
     */
    public String getParentById(TreeEntity<?> entity, Serializable id) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entity.getClass());
        String tableName = tableInfo.getTableName();
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(tableName).append("\n");
        sql.append("where id = ( select parent_id from ").append(tableName).append(" where id = '").append(id).append("')");
        if(SqlInjectionUtils.check(id.toString())) {
            throw new ServiceException("非法脚本，请检查脚本:" + sql);
        }
        return sql.toString();
    }

}
